#include "thread.h"

CThread::CThread()
: m_id(0)
#ifdef WIN32
, m_handle(NULL)
#endif
, m_address(NULL)
{
}

CThread::~CThread()
{
    Stop();
}

bool CThread::Start(update_thread_address* address, void* param, int stacksize)
{
    Stop();

    m_address = address;

#ifdef WIN32

    m_handle = (HANDLE)_beginthreadex(NULL, stacksize, address, param, 0, &m_id);

    if(NULL == m_handle)
        return false;
#else

    pthread_attr_t  attr;
    
    pthread_attr_init(&attr);
    
    pthread_attr_setstacksize(&attr, stacksize);
    
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    pthread_create(&m_id, &attr, address, param);
    
    pthread_attr_destroy(&attr);
    
    if(0 == m_id)
        return false;

#endif

    return true;
}

void CThread::Stop()
{
#ifdef WIN32

    if(NULL != m_handle)
    {
        DWORD dwExitCode;
        
        GetExitCodeThread(m_handle, &dwExitCode); // should be STILL_ACTIVE = 0x00000103 = 259

        CloseHandle(m_handle);

        m_handle = NULL;
    }

#else

    if(0 != m_id)
    {
        pthread_cancel(m_id);

        void* ret_val = NULL;

        pthread_join(m_id, &ret_val);

        m_id = 0;
    }

#endif
}
